package com.spring.api.web.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.spera.genutil.TokenUtil;
import com.spring.api.web.dao.ApiUserDetailMapper;
import com.spring.api.web.model.ApiUser;
import com.spring.api.web.service.UserApiService;
import com.spring.security.core.context.JedisCont;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.MD5Util;
import com.spring.security.core.util.PWD;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.dao.RoleMapper;
import com.spring.security.web.dao.UserMapper;
import com.spring.security.web.model.User;

@Service
public class UserApiServiceImpl implements UserApiService {

	@Resource
	private ApiUserDetailMapper apiUserDetailMapper;

	@Resource
	private JedisCache jedisCache;

	@Resource
	private UserMapper userMapper;

	@Resource
	private RoleMapper roleMapper;

	@Override
	public Map<String, Object> login(String token, String userName,
			String passWord) {
		Map<String, Object> m = ApplicationUtils.getDataSet();
		try {
			if (ApplicationUtils.isNotNull(token)) {
				Map<String, Object> s = TokenUtil.checkToken(token,jedisCache);
				if(ApplicationUtils.isNotNull(s)){
					return s;
				}else{
					m.put("token", token);
					m.put("status", "1");
					m.put("msg", "登录成功");
					return m;
				}
					
//				if (this.redisCache.exists(token)) {
//					String user_id = this.redisCache.get(token);
//
//					this.redisCache.setEx(token, JedisCont.JEDIS_EXPRISE,
//							user_id);
//
//					m.put("token", token);
//					m.put("status", "1");
//					m.put("msg", "登录成功");
//					return m;
//				}
//				m.put("status", "-9999");
//				m.put("msg", "登录已失效，请重新登录");
//				return m;
			}
			
			

			if ((!ApplicationUtils.isNotNull(userName))
					|| (!ApplicationUtils.isNotNull(passWord))) {
				m.put("status", "0");
				m.put("msg", "用户名或密码不能为空");
				return m;
			}
			User s = new User();
			if (ApplicationUtils.validateEmail(userName))
				s.setEmail(userName);
			else if (ApplicationUtils.validatePhone(userName))
				s.setPhone(userName);
			else {
				s.setUsername(userName);
			}

			List<User> list = this.userMapper.selectByWhereStr(s);
			User authUserInfo = null;
			if ((ApplicationUtils.isNotNull(list)) && (list.size() != 0)) {
				authUserInfo = (User) list.get(0);
			}
			if (!ApplicationUtils.isNotNull(authUserInfo)) {
				m.put("status", "0");
				m.put("msg", "用户名不存在");
				return m;
			}
			if (!passWord.equalsIgnoreCase(authUserInfo.getPassword())) {
				m.put("status", "0");
				m.put("msg", "密码错误");
				return m;
			}
			String user_uuid = MD5Util
					.string2MD5(ApplicationUtils.randomUUID());

			this.jedisCache.setEx(user_uuid, JedisCont.JEDIS_EXPRISE,
					authUserInfo.getId());
			token = user_uuid;
			m.put("token", token);
			m.put("status", "1");
			m.put("msg", "登录成功");
			ApiUser dataSet = this.apiUserDetailMapper
					.selectUserDetail(authUserInfo.getId());
			m.put("dataset", dataSet);
		} catch (Exception e) {
			e.printStackTrace();
			m.put("status", "0");
			m.put("msg", "登录失败");
		}

		return m;
	}
	
	@Override
	public Map<String, Object> register(User user, MultipartFile file) {
		String role_id = "1";
		Map<String, Object> m = new HashMap<String, Object>();
		if (!user.getPassword().equals(user.getPassword_again())) {
			m.put("status", "0");
			m.put("msg", "密码两次输入不一致");
			return m;
		}
		if (!ApplicationUtils.isNotNull(role_id)) {
			m.put("status", "0");
			m.put("msg", "请选择角色");
			return m;
		}
		String user_id = ApplicationUtils.randomUUID();
		user.setId(user_id);
		user.setState("1");
		try {
			User s = new User();
			s.setUsername(user.getUsername());
			List<User> list = this.userMapper.selectByWhereStr(user);
			User is_exists = null;
			if ((ApplicationUtils.isNotNull(list)) && (list.size() != 0)) {
				is_exists = (User) list.get(0);
			}

			if (ApplicationUtils.isNotNull(is_exists)) {
				m.put("status", "0");
				m.put("msg", "用户已存在");
				return m;
			}
			if (!file.isEmpty()) {
				String fileName = file.getOriginalFilename();
				Date d = new Date();
				SimpleDateFormat tempDate = new SimpleDateFormat(
						"yyyyMMddHHmmss");
				String newfilename = tempDate.format(d) + "_" + fileName;
				Integer fileSize = Integer.valueOf(0);
				File filePath = null;
				byte[] bytes = file.getBytes();
				fileSize = Integer.valueOf((int) file.getSize() / 1024);
				if (fileSize.intValue() <= 102400) {
					String uploadPath = "\\upload\\";

					if (!new File(uploadPath).isDirectory()) {
						new File(uploadPath).mkdir();
					}
					uploadPath = uploadPath + newfilename;
					filePath = new File(uploadPath);
					FileCopyUtils.copy(bytes, filePath);
					user.setImage_src(JedisCont.APP_ADDRESS + newfilename);
				} else {
					m.put("status", "0");
					m.put("msg", "上传的文件太大，文件大小不能超过10M");
					return m;
				}
			}
			int in = insert(user, role_id);
			if (in == 1) {
				String user_uuid = PWD.createNewPassword(ApplicationUtils
						.randomUUID());
				this.jedisCache.setEx(user_uuid, JedisCont.JEDIS_EXPRISE,
						user_id);
				String token = user_uuid;
				m.put("token", token);
				m.put("status", "1");
				m.put("msg", "注册成功");
			} else {
				m.put("status", "0");
				m.put("msg", "数据保存异常");
			}
			ApiUser dataSet = this.apiUserDetailMapper
					.selectUserDetail(user_id);
			m.put("dataSet", dataSet);
		} catch (Exception e) {
			e.printStackTrace();
			m.put("status", "0");
			m.put("msg", "用户注册失败");
		}
		return m;
	}

	public int insert(User model, String role_id) {
		int u = this.userMapper.insertSelective(model);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("user_id", model.getId());
		m.put("role_id", role_id);
		int r = this.roleMapper.insertUserRole(m);
		int ret = 0;
		if ((u == 1) && (r == 1)) {
			ret = 1;
		}
		return ret;
	}

	@Override
	public Map<String, Object> register(User user) {
		//默认角色为1=家长
		String role_id = "1";
		Map<String, Object> m = new HashMap<String, Object>();
		//判断token
//		if (ApplicationUtils.isNotNull(user.getToken())) {
//			Map<String, Object> s = checkToken(user.getToken());
//			if(ApplicationUtils.isNotNull(s)){
//				return s;
//			}
//		}
		
		if (!user.getPassword().equals(user.getPassword_again())) {
			m.put("status", "0");
			m.put("msg", "密码两次输入不一致");
			return m;
		}
		if (!ApplicationUtils.isNotNull(role_id)) {
			m.put("status", "0");
			m.put("msg", "请选择角色");
			return m;
		}
		String user_id = ApplicationUtils.randomUUID();
		user.setId(user_id);
		user.setState("1");
		try {
			User s = new User();
			if (ApplicationUtils.isNotNull(user.getUsername())) {
				String path = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{3,15}$";
				if (ApplicationUtils.match(user.getUsername(), path)) {
					s.setUsername(user.getUsername());
				} else {
					m.put("status", "0");
					m.put("msg", "用户名格式有误，用户名只有4-15数字和字母组成");
					return m;
				}
			} else if (ApplicationUtils.isNotNull(user.getPhone())) {
				if (ApplicationUtils.validatePhone(user.getPhone())) {
					s.setPhone(user.getPhone());
				} else {
					m.put("status", "0");
					m.put("msg", "请输入正确的手机号");
					return m;
				}
			} else if (ApplicationUtils.isNotNull(user.getEmail())) {
				if (ApplicationUtils.validateEmail(user.getEmail())) {
					s.setEmail(user.getEmail());
				} else {
					m.put("status", "0");
					m.put("msg", "请输入正确的邮箱地址");
					return m;
				}
			} else {
				m.put("status", "0");
				m.put("msg", "请输入用户名");
				return m;
			}
			List<User> list = this.userMapper.selectByWhereStr(s);
			User is_exists = null;
			if ((ApplicationUtils.isNotNull(list)) && (list.size() != 0)) {
				is_exists = (User) list.get(0);
			}

			if (ApplicationUtils.isNotNull(is_exists)) {
				m.put("status", "0");
				m.put("msg", "用户已存在");
				return m;
			}
			int in = insert(user, role_id);
			if (in == 1) {
				String user_uuid = MD5Util.string2MD5(ApplicationUtils
						.randomUUID());
				this.jedisCache.setEx(user_uuid, JedisCont.JEDIS_EXPRISE,
						user_id);
				String token = user_uuid;
				m.put("token", token);
				m.put("status", "1");
				m.put("msg", "注册成功");
			} else {
				m.put("status", "0");
				m.put("msg", "数据保存异常");
			}
			ApiUser dataSet = this.apiUserDetailMapper
					.selectUserDetail(user_id);
			m.put("dataSet", dataSet);
		} catch (Exception e) {
			e.printStackTrace();
			m.put("status", "0");
			m.put("msg", "用户注册失败");
		}
		return m;
	}

//	private Map<String, Object> checkToken(String token) {
//		Map<String, Object> s = new HashMap<String, Object>();
//		if (!ApplicationUtils.isNotNull(token)) {
//			s.put(ApplicationUtils.STATUS, "0");
//			s.put(ApplicationUtils.MSG, "请先登录");
//			return s;
//		} else {
//			if (!jedisCache.exists(token)) {
//				s.put(ApplicationUtils.STATUS, "-9999");
//				s.put(ApplicationUtils.MSG, "用户登录已失效，请先重新登录");
//				return s;
//			} else{
//				jedisCache.expire(token, JedisCont.JEDIS_EXPRISE);
//				return null;
//			}
//		}
//	}

	/**
	 * 密码修改
	 */
	@Override
	public Map<String,Object> changePwd(String token,
			String pwd_token,
			String pwd_valnum,
			String oldpwd, 
			String newpwd,
			String newpwddb) {
		Map<String, Object> s = TokenUtil.checkToken(token,jedisCache);
		if(ApplicationUtils.isNotNull(s))
			return s;
		s = new HashMap<String, Object>();
		
		if (!ApplicationUtils.isNotNull(newpwd)||!ApplicationUtils.isNotNull(newpwddb)) {
			s.put(ApplicationUtils.STATUS, "0");
			s.put(ApplicationUtils.MSG, "密码不可为空");
			return s;
		}
		if (!newpwd.equals(newpwddb)) {
			s.put(ApplicationUtils.STATUS, "0");
			s.put(ApplicationUtils.MSG, "密码两次输入不一致");
			return s;
		}
		
		String user_id = jedisCache.hget(token,TokenUtil.USER_ID);
		User u = new User();
		u.setId(user_id);
		
		List<User> list = userMapper.selectByWhereStr(u);
		
		if (!ApplicationUtils.isNotNull(list)||list.size()==0) {
			s.put(ApplicationUtils.STATUS, "0");
			s.put(ApplicationUtils.MSG, "用户名不存在");
			return s;
		}
		
		if ((ApplicationUtils.isNotNull(list)) && (list.size() != 0)) {
			u = (User) list.get(0);
		}
		
		//密码找回与密码修改的区别
		if(ApplicationUtils.isNotNull(oldpwd)){
			if(!oldpwd.equals(u.getPassword())){
				s.put(ApplicationUtils.STATUS, "0");
				s.put(ApplicationUtils.MSG, "密码输入不正确");
				return s;
			}
		}else{
			if(!ApplicationUtils.isNotNull(pwd_token)){
				s.put(ApplicationUtils.STATUS, "0");
				s.put(ApplicationUtils.MSG, "验证码不正确");
				return s;
			}
			
			if(!ApplicationUtils.isNotNull(pwd_valnum)){
				s.put(ApplicationUtils.STATUS, "0");
				s.put(ApplicationUtils.MSG, "验证码不能为空");
				return s;
			}
			
			if(!jedisCache.exists(pwd_token)){
				s.put(ApplicationUtils.STATUS, "0");
				s.put(ApplicationUtils.MSG, "验证码已失效，请重新发送");
				return s;
			}
			
			String val_num = jedisCache.lindex(pwd_token, 0);
			String val_token = jedisCache.lindex(pwd_token, 1);
			if(!val_token.equals(token)){
				s.put(ApplicationUtils.STATUS, "0");
				s.put(ApplicationUtils.MSG, "此验证码不归该用户所有，请重新发送");
				return s;
			}
			
			if(!val_num.equals(pwd_valnum)){
				s.put(ApplicationUtils.STATUS, "0");
				s.put(ApplicationUtils.MSG, "验证码不一致");
				return s;
			}
		}
		
		User nu = new User();
		nu.setId(user_id);
		nu.setPassword(newpwd);
		int uu = userMapper.updateByPrimaryKeySelective(nu);
		if(uu>0){
			s.put(ApplicationUtils.STATUS, "1");
			s.put(ApplicationUtils.MSG, "密码修改成功");
		}else{
			s.put(ApplicationUtils.STATUS, "0");
			s.put(ApplicationUtils.MSG, "密码修改失败");
		}
		return s;
	}
	
	/**
	 * 发送验证码
	 */
	public Map<String, Object> sendPwdToken(String token){
		Map<String, Object> s = TokenUtil.checkToken(token,jedisCache);
		if(ApplicationUtils.isNotNull(s))
			return s;
		s = new HashMap<String, Object>();
		String pwd_token = ApplicationUtils.randomUUID();
		int[] arrNum = ApplicationUtils.randomArray(0, 9, 6);
		String pwd_valnum = String.valueOf(arrNum[0])+
				String.valueOf(arrNum[1])+
				String.valueOf(arrNum[2])+
				String.valueOf(arrNum[3])+
				String.valueOf(arrNum[4])+
				String.valueOf(arrNum[5]);
		jedisCache.lpush(pwd_token, token);
		jedisCache.lpush(pwd_token, pwd_valnum);
		jedisCache.expire(pwd_token, 1800);
		s.put("pwd_token", pwd_token);
		s.put("pwd_valnum", pwd_valnum);
		s.put(ApplicationUtils.STATUS, "1");
		s.put(ApplicationUtils.MSG, "验证码发送成功");
		return s;
	}
}